package com.catazy.ocrdemo.ui.activity.scan.fragment.crop

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.PointF
import android.os.Bundle
import android.util.Log
import android.view.View
import com.catazy.cameralib.util.OpenCvBridge
import com.catazy.mvvmlib.base.fragment.BaseVmVbFragment
import com.catazy.mvvmlib.ext.view.click
import com.catazy.ocrdemo.R
import com.catazy.ocrdemo.databinding.FragmentImageCropBinding
import com.catazy.ocrdemo.entity.ScanResult
import com.catazy.ocrdemo.ui.activity.scan.AppScanActivity
import com.king.camera.scan.util.LogUtils
import id.zelory.compressor.determineImageRotation

/**
 * 作者: Tao
 * 日期: 2024/3/15
 * 时间: 14:41
 * 描述: 图片裁剪
 */
class ImageCropFragment : BaseVmVbFragment<ImageCropViewModel, FragmentImageCropBinding>() {

    private var selectedImage: Bitmap? = null
    private var scanResult: ScanResult? = null

    override fun initView(savedInstanceState: Bundle?) {

        scanResult = getAppScanActivity()?.getScanResult()
        val path = scanResult?.imagePath
        val sourceBitmap = BitmapFactory.decodeFile(path)
        sourceBitmap?.let {
            selectedImage =
                determineImageRotation(com.blankj.utilcode.util.FileUtils.getFileByPath(path), it)
        }

        mDatabind.holderImageView.post {
            initCropping()
        }

        mDatabind.cropBack.click {
            LogUtils.i("关闭当前页")
            getAppScanActivity()?.closeFragment()
        }

        mDatabind.cropDone.click {
            LogUtils.i("打印日志")
            mDatabind.cropPolygonView.logPoint()
            getCroppedImage()
            getAppScanActivity()?.showImageProcessFragment()
        }
    }

    private fun initCropping() {
        if (selectedImage != null && selectedImage!!.width > 0 && selectedImage!!.height > 0) {
            LogUtils.i("selectedImage width: ${selectedImage!!.width} height: ${selectedImage!!.height}")
//            val scaledBitmap: Bitmap = selectedImage!!.scaledBitmap(
//                mDatabind.holderImageCrop.width,
//                mDatabind.holderImageCrop.height
//            )
//            LogUtils.i("scaledBitmap width: ${scaledBitmap.width} height: ${scaledBitmap.height}")
            mDatabind.imagePreview.setImageBitmap(selectedImage)
//            val tempBitmap = (mDatabind.imagePreview.drawable as BitmapDrawable).bitmap
////            val pointFs = getEdgePoints(tempBitmap)
////            Log.d(TAG, "ZDCgetEdgePoints ends ${System.currentTimeMillis()}")
            mDatabind.cropPolygonView.setPoint(scanResult?.rect!!)
            mDatabind.cropPolygonView.visibility = View.VISIBLE
//            val padding = resources.getDimension(R.dimen.dp_32).toInt()
//            val layoutParams =
//                FrameLayout.LayoutParams(tempBitmap.width + padding, tempBitmap.height + padding)
//            layoutParams.gravity = Gravity.CENTER
//            mDatabind.cropPolygonView.layoutParams = layoutParams
        }
    }

    private fun getCroppedImage() {
        if (selectedImage != null) {
            try {
                val points: Map<Int, PointF> = mDatabind.cropPolygonView.getPoints()
                val xRatio: Float = selectedImage!!.width.toFloat() / mDatabind.imagePreview.width
                val yRatio: Float = selectedImage!!.height.toFloat() / mDatabind.imagePreview.height
                val pointPadding = requireContext().resources.getDimension(R.dimen.dp_20).toInt()
                val x1: Float = (points.getValue(0).x + pointPadding) * xRatio
                val x2: Float = (points.getValue(1).x + pointPadding) * xRatio
                val x3: Float = (points.getValue(2).x + pointPadding) * xRatio
                val x4: Float = (points.getValue(3).x + pointPadding) * xRatio
                val y1: Float = (points.getValue(0).y + pointPadding) * yRatio
                val y2: Float = (points.getValue(1).y + pointPadding) * yRatio
                val y3: Float = (points.getValue(2).y + pointPadding) * yRatio
                val y4: Float = (points.getValue(3).y + pointPadding) * yRatio

                getAppScanActivity()?.setCroppedImage(
                    OpenCvBridge.instance.getScannedBitmap(
                        selectedImage!!,
                        x1,
                        y1,
                        x2,
                        y2,
                        x3,
                        y3,
                        x4,
                        y4
                    )
                )
            } catch (e: java.lang.Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun getAppScanActivity(): AppScanActivity? {
        return activity as? AppScanActivity
    }
}